package edu.tyut.game.ui.community

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import edu.tyut.game.GameApplication
import edu.tyut.game.R
import edu.tyut.game.logic.model.Comment
import edu.tyut.game.logic.model.FriendCircle
import edu.tyut.game.logic.network.ServiceCreator
import edu.tyut.game.utils.LogUtils


class FriendCircleAdapter(
    private val context: Context,
    private val friendCircles: MutableList<FriendCircle>,
    private val viewModel: CommunityViewModel,
    private val fragment: CommunityFragment,
) : RecyclerView.Adapter<FriendCircleAdapter.ViewHolder>() {

    private val tag = this::class.java.name

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val headImage: ImageView = view.findViewById(R.id.headImg)
        val username: TextView = view.findViewById(R.id.username)
        val gender: TextView = view.findViewById(R.id.gender)
        val deleteFriendCircle: LinearLayout = view.findViewById(R.id.deleteFriendCircle)
        val updateFriendCircle: LinearLayout = view.findViewById(R.id.updateFriendCircle)
        val content: TextView = view.findViewById(R.id.content)
        val images: RecyclerView = view.findViewById(R.id.images)
        val like: ImageView = view.findViewById(R.id.like)
        val likeCount: TextView = view.findViewById(R.id.likeCount)
        val comment: ImageView = view.findViewById(R.id.comment)
        val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.circle_item, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = friendCircles.size

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val friendCircle = friendCircles[position]
        // ==============  观察者 contents ==================
        // 展示评论
        fragment.showComment(holder, friendCircle.id)
        // ===================================
        // 头像
        Glide.with(context).load("${ServiceCreator.BASE_URL}${friendCircle.avatarPath}")
            .into(holder.headImage)
        LogUtils.d(tag, "FriendCircleAdapter: ${ServiceCreator.BASE_URL}${friendCircle.avatarPath}")
        // 用户名
        holder.username.text = friendCircle.username
        // 性别
        holder.gender.text = friendCircle.gender
        // 内容
        holder.content.text = friendCircle.content
        // 图像
        val gson = Gson()
        val urls = gson.fromJson<List<String>>(friendCircle.images, List::class.java)
        // 添加urls
        val gridLayoutManager = GridLayoutManager(context, 3, RecyclerView.VERTICAL, false)
        gridLayoutManager.orientation = RecyclerView.VERTICAL
        holder.images.layoutManager = gridLayoutManager
        holder.images.adapter = ImageViewAdapter(context, urls)
        // 点赞数
        holder.likeCount.text = friendCircle.likeCounts.toString()
        // 监听
        // 编辑朋友圈
        // 编辑朋友圈
        /*
            val editView = LayoutInflater.from(context).inflate(R.layout.dialog_post_friend_circle, null)
            val content: TextView = editView.findViewById(R.id.content)
            val images: RecyclerView = editView.findViewById(R.id.images)

            val postImageViewGridLayoutManager = GridLayoutManager(context, 3, RecyclerView.VERTICAL, false)
            postImageViewGridLayoutManager.orientation = RecyclerView.VERTICAL
            images.layoutManager = postImageViewGridLayoutManager

            val mutableList = mutableListOf<Uri>()
            val pickMultipleMedia =
                activity.registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(9)) { uris ->
                    if (uris.isNotEmpty()) {
                        Log.d("PhotoPicker", "Number of items selected: ${uris.size}")
                        mutableList.addAll(uris.toMutableList())
                        val adapter = PostImageViewAdapter(context, mutableList)
                        images.adapter = adapter
                        holder.updateFriendCircle.callOnClick()
                    } else {
                        Log.d("PhotoPicker", "No media selected")
                    }
                }
            val dialog = AlertDialog.Builder(context)
                .setIcon(R.drawable.image5)
                .setTitle("友好评论😊")
                .setView(editView)
                .setCancelable(false)
                .setNegativeButton("取消") { dialog, which ->
                    run {
                        Toast.makeText(context, "您点击了取消", Toast.LENGTH_SHORT).show()
                        Log.d(tag, "对话框，取消按钮: $which")
                        dialog.cancel()
                    }
                }
                .setPositiveButton("发布") { dialog, which ->
                    val uid = GameApplication.loginUser?.id ?: 0
                    val username = GameApplication.loginUser?.username ?: "admin"
                    val gender = GameApplication.loginUser?.gender ?: "男"
                    val avatarPath = GameApplication.loginUser?.avatarPath
                    val contentNew = content.text.toString().trim()
                    if (contentNew.isEmpty() || contentNew.isBlank()) return@setPositiveButton
                    val friendCircleNew = FriendCircle(friendCircle.id, uid, username, gender, avatarPath ?: "image/image.jpg", contentNew, "", friendCircle.likeCount)
                    // TODO 更新朋友圈
                    updateFriendCircle(mutableList, friendCircleNew)
                    friendCircles[position] = friendCircleNew
                    this.notifyItemChanged(position)
                    Toast.makeText(context, "您点击了发布", Toast.LENGTH_SHORT).show()
                    Log.d(tag, "对话框，发布按钮: $which")
                    Log.d(tag, "对话框，发布按钮: ${content.text}")
                    dialog.dismiss()
                }
                .setNeutralButton("选择照片") { _, which ->
                    Toast.makeText(context, "您点击了选择照片", Toast.LENGTH_SHORT).show()
                    Log.d(tag, "对话框，选择照片: $which")
                    // dialog.dismiss()
                    pickMultipleMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
                }
                .create()
            dialog.setCanceledOnTouchOutside(false)
        */
        if (GameApplication.loginUser?.id == friendCircle.uid){
            holder.updateFriendCircle.visibility = View.VISIBLE
        }else{
            holder.updateFriendCircle.visibility = View.INVISIBLE
        }
        holder.updateFriendCircle.setOnClickListener {
            // 这里启动一个Dialog
            UpdatePostFriendCircleActivity.actionStart(context, friendCircle)
        }
        if (GameApplication.loginUser?.id == friendCircle.uid){
            holder.deleteFriendCircle.visibility = View.VISIBLE
        }else{
            holder.deleteFriendCircle.visibility = View.INVISIBLE
        }
        // 删除朋友圈
        val dialogDel = AlertDialog.Builder(context)
            .setIcon(R.drawable.image5) // 设置标题的图片
            .setTitle("删除朋友圈😊") // 设置对话框的标题
            .setMessage("是否要删除朋友圈😥？") // 设置对话框内容
            .setNegativeButton("取消") { dia, which ->
                run {
                    Toast.makeText(context, "您取消了删除朋友圈对话框😊", Toast.LENGTH_LONG)
                        .show()
                    LogUtils.d(tag, "对话框，取消按钮: $which")
                    dia.cancel()
                }
            }
            .setPositiveButton("确定") { dia, which ->
                Toast.makeText(context, "删除朋友圈成功😁", Toast.LENGTH_SHORT).show()
                LogUtils.d(tag, "对话框，确定按钮: $which")
                dia.dismiss()
                friendCircles.removeAt(position)
                this.notifyItemRemoved(position)
                viewModel.deleteFriendCircle(friendCircle.id)
            }
            .create()
        holder.deleteFriendCircle.setOnClickListener {
            // Dialog
            dialogDel.show()
        }
        // 点赞
        // =========================
        var likeFlag = false
        holder.like.setOnClickListener {
            if (!likeFlag) {
                Toast.makeText(context, "点赞", Toast.LENGTH_LONG).show()
                holder.like.setImageDrawable(
                    AppCompatResources.getDrawable(
                        context,
                        R.drawable.like_red
                    )
                )
                viewModel.addFriendCircleLike(friendCircle.id)
                holder.likeCount.text = "${holder.likeCount.text.toString().trim().toInt() + 1}"
            } else {
                Toast.makeText(context, "取消点赞", Toast.LENGTH_LONG).show()
                holder.like.setImageDrawable(
                    AppCompatResources.getDrawable(
                        context,
                        R.drawable.like
                    )
                )
                viewModel.subFriendCircleLike(friendCircle.id)
                holder.likeCount.text = "${holder.likeCount.text.toString().trim().toInt() - 1}"
            }
            likeFlag = !likeFlag
        }
        // 监听评论
        val commentView = LayoutInflater.from(context).inflate(R.layout.send_comment_item, null)
        val comment: EditText = commentView.findViewById(R.id.content)
        val send: Button = commentView.findViewById(R.id.send)
        val dialogComment = AlertDialog.Builder(context)
            .setIcon(R.drawable.image5)
            .setTitle("友好评论😊")
            .setView(commentView)
            .create()
        comment.addTextChangedListener {
            val con = comment.text.toString().trim()
            send.isClickable = con.isNotBlank() && con.isNotEmpty()
        }
        send.setOnClickListener {
            // 默认会调用 send.isClickable = true
            val con = comment.text.toString().trim()
            Log.i(tag, "$con isBank? ${con.isBlank()}")
            Toast.makeText(context, con, Toast.LENGTH_SHORT).show()
            dialogComment.dismiss()
            // 添加评论
            val username = GameApplication.loginUser?.username ?: "admin"
            val avatarPath = GameApplication.loginUser?.avatarPath ?: "/image/image.jpg"
            LogUtils.d(tag, avatarPath)
            val commentNew =
                Comment(
                    0,
                    username,
                    avatarPath,
                    friendCircle.id,
                    con,
                    username,
                    friendCircle.username,
                    0
                )
            // TODO 发送评论
            viewModel.postComment(commentNew)
            viewModel.queryFriendCircle("DESC")
        }
        send.isClickable = false
        holder.comment.setOnClickListener {
            LogUtils.d(tag, "点击发送消息... : $position")
            dialogComment.show()
        }

    }
}